<template>
	<view style="padding-top: var(--status-bar-height);">
		<view class="flex position-relative" style="background-color: var(--theme-box-bg);line-height: 44px;">
			<view :class="['text-align-center', activeTabIndex==1?'active':'']" style="width: 50%;"
				@click="switchTab(1)">{{$t('personal.text20')}}</view>
			<view :class="['text-align-center', activeTabIndex==2?'active':'']" style="width: 50%;"
				@click="switchTab(2)">{{$t('personal.text21')}}</view>
			<view class="underline" :style="{transform: `translate(${activeTabIndex==1?'86':'276'}px)`}"></view>
		</view>
		<!-- 加载动画 -->
		<!-- <loadIcon v-show="loading"></loadIcon> -->
		<view class="" v-show="loading" style="text-align: center;">
			loading ...
		</view>
		<!-- 空展示图片 -->
		<view class="list" v-show="list.length > 0">
			<view class="" v-show="activeTabIndex==1">
				<view class="item radius-12 fs12 up-bg" v-for="(item,index) in list" :key="index"
					style="background-color: var(--theme-box-bg);">
					<view class="flex-between">
						<view class="">
							<text>{{item.name}}</text> <br />
							<text>{{item.buyprice}}</text>
						</view>
						<view class="">
							<text
								:class="item.otype==1?'text-up':'text-down'">{{item.otype==1?$t('product.text5'):$t('product.text6')}}
								<text> (¥{{item.price}})</text></text> <br />
							<text>{{formatTime(item.buytime*1000)}}</text>
						</view>
						<view class="">
							<text :class="item.otype==1?'text-up':'text-down'">{{item.result}}</text> <br />
							<CountdownItem :endTimestamp="(item.buytime+item.stime)*1000"></CountdownItem>
						</view>
					</view>
				</view>
			</view>
			<view class="" v-show="activeTabIndex==2">
				<view class="item radius-12 text-des-color fs12 up-bg" v-for="(item,index) in list" :key="index"
					style="background-color: var(--theme-box-bg);">
					<!-- <view class="flex-between">
						<view class="">
							<text class="fb">{{item.name}}</text> <br />
							<view class="fs12">
								<text>{{item.buyprice}}</text>-
								<text :class="item.otype==1?'text-up':'text-down'">{{item.sellprice}}</text>
							</view>
						</view>
						<view class="">
							<text :class="item.otype==1?'text-up':'text-down'">{{item.otype==1?$t('product.text5'):$t('product.text6')}} <text> (¥{{item.price}})</text></text> <br />
							<text class="fs10">{{formatTime(item.buytime*1000)}}</text>
						</view>
						<view class="" style="text-align: right;">
							<text :class="item.otype==1?'text-up':'text-down'">{{item.ploss}}</text> <br/>
							<view class="fs10">{{formatTime(item.selltime*1000)}}</view>
						</view>
					</view> -->
					<view class="title fb flex-between text-main-color fs14">
						<view class="flex">
							<text>{{item.name}}</text>
							<view class="text-sm sj" style="margin-left: 5px;color: #fc6d22;">
								{{item.stime}}S
							</view>
						</view>
						<text
							:class="item.otype==1?'text-up':'text-down'">{{item.otype==1?$t('product.text5'):$t('product.text6')}}</text>
					</view>
					<view class="flex mt10">
						<text>{{$t('personal.text17')}}</text>
						<text style="margin-left: 10px;">{{item.orderno}}</text>
					</view>
					<view class="flex flex-wrap">
						<view class="else flex mt5 text-main-color fb">
							<text>{{$t('product.text7')}}</text>
							<text>{{item.price}}CNY</text>
						</view>
						<view class="else flex mt5 text-main-color fb">
							<text>{{$t('product.ploss')}}</text>
							<text class="text-down">{{item.ploss}}</text>
						</view>
						<view class="else flex mt5">
							<text>{{$t('product.buyprice')}}</text>
							<text>{{item.buyprice}}</text>
						</view>
						<view class="else flex mt5">
							<text>{{$t('product.dealPrice')}}</text>
							<text>{{item.sellprice}}</text>
						</view>
						<view class="else mt5">
							<view>{{$t('product.holdStoxckTime')}}</view>
							<view>{{formatTime(item.buytime*1000)}}</view>
						</view>
						<view class="else mt5">
							<view>{{$t('product.pingStoxckTime')}}</view>
							<view>{{formatTime(item.selltime*1000)}}</view>
						</view>
					</view>
				</view>
			</view>
			<uni-load-more :status="loadStatus" :contentText="contentText" @clickLoadMore="loadMore"></uni-load-more>
		</view>
		<view class="list p-lr-16" v-show="list.length == 0 && !loading">
			<view class="empty flex-column">
				<image src="/static/dd.png" mode=""></image>
				<text class="fs14">{{$t('personal.text22')}}</text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		onMounted,
		ref,
		onUnmounted,
		onBeforeUnmount
	} from "vue"
	import loadIcon from "@/components/loadIcon.vue";
	import {
		getOrderList
	} from "@/api";
	import {
		formatTime
	} from '@/utils/utils.js'
	import {
		onReachBottom,
		onShow
	} from '@dcloudio/uni-app'
	import useGlobalProperties from '@/utils/useGlobalProperties.js'
	import CountdownItem from '@/components/CountdownItem.vue'
	const {
		$t,
		$i18n
	} = useGlobalProperties()
	const activeTabIndex = ref(1)
	const list = ref([])
	const page = ref(1)
	const loading = ref(false)
	const loadStatus = ref('loading')
	const finished = ref(false)
	const contentText = {
		contentdown: $t('loadMore'),
		contentrefresh: $t('loading'),
		contentnomore: $t('noMore')
	}
	const switchTab = (index) => {
		// if(index === activeTabIndex.value) return;
		activeTabIndex.value = index
		page.value = 1
		list.value = []
		loadStatus.value = 'loading'
		finished.value = false
		if (index == 2) {
			clearAll();
		}
		loadMore()
	}
	const startCountdown = (targetTimestamp) => {
		// console.log('function startCountdown',)
		// console.log('function startCountdown targetTimestamp', targetTimestamp)
		let result = null
		const interval = setInterval(() => {
			const currentTimestamp = Date.now(); // 获取当前时间戳（毫秒）
			const diff = targetTimestamp - currentTimestamp; // 计算时间差（毫秒）
			// console.log('时间差', diff)
			if (diff <= 0) {
				result = null
				clearInterval(interval); // 倒计时结束，清除计时器
				// console.log("倒计时结束");
				return false;
			}

			// 计算剩余的天、时、分、秒
			const days = Math.floor(diff / (1000 * 60 * 60 * 24));
			const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
			const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
			const seconds = Math.floor((diff % (1000 * 60)) / 1000);

			// 格式化显示
			const formattedTime =
				`${days} ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

			// console.log(formattedTime); // 在控制台显示倒计时
			result = formattedTime
			return formattedTime;
			// 你也可以在页面中动态更新倒计时
			// const countdownElement = document.getElementById("countdown");
			// if (countdownElement) {
			//   countdownElement.textContent = formattedTime;
			// }
		}, 1000);
		return result
	}


	const loadMore = () => {
		if (finished.value) return;
		if (loading.value) return;
		loading.value = true
		getOrderList({
			page: page.value++,
			type: activeTabIndex.value
		}).then(res => {
			// console.log('订单列表 res',res);
			loading.value = false
			if (res.data.length == 0) {
				finished.value = true
				loadStatus.value = 'noMore'
			} else {
				loadStatus.value = res.data.length == 10 ? 'more' : 'noMore'
				if (page.value === 1) {
					list.value = res.data; // 直接赋值，避免拼接
				} else {
					list.value = list.value.concat(res.data); // 分页拼接
				}
				if (activeTabIndex.value == 1) {
					startTimers()
				}
				// console.log('list.value',list.value);
			}
		})
	}
	onReachBottom(() => {
		// console.log("触底了");
		if (finished.value || loading.value) return; // 如果已加载完或正在加载，则不执行
		loadMore();
	})
	onShow(() => {
		loadMore();
	})
	// onMounted(() =>{
	// 	loadMore();
	// })
	function getRandomInt(min, max) {
		if (typeof min !== 'number' || typeof max !== 'number') {
			throw new TypeError('参数必须是数字');
		}

		min = Math.ceil(min); // 向上取整
		max = Math.floor(max); // 向下取整
		const range = max - min + 1; // 计算区间范围
		return Math.floor(Math.random() * range) + min;
	}
	const startTimers = () => {
		list.value.forEach((item, index) => {
			item.timer = setInterval(() => { // 将 timer ID 保存在 item 中
				const endtime = (item.buytime + item.stime) * 1000;
				let now = Date.now();
				let remainingTime = Math.max(0, endtime - now);

				if (remainingTime > 0) {
					item.result = getRandomInt(item.rand_1, item.rand_2); // 直接更新 item.result
					// console.log(`Item ${index} result:`, item.result);
				} else {
					clearInterval(item.timer); // 清除定时器
					//   list.value.splice(index, 1); //  避免直接修改数组， 采用filter
					list.value = list.value.filter((_, i) => i !== index);
					// console.log(`Item ${index} removed`);
				}
			}, 1000);
		});
	};
	const clearAll = () => {
		list.value.forEach(item => {
			if (item.timer) {
				clearInterval(item.timer);
			}
		});
	}
	onBeforeUnmount(() => {
		clearAll();
	})
	onUnmounted(() => {
		// 组件卸载时清除所有定时器
		clearAll();
	});
</script>

<style scoped lang="scss">
	page {
		background: radial-gradient(circle at 70% 40%, #1A4B4B);
	}

	.underline {
		position: absolute;
		bottom: 4px;
		height: 4px;
		width: 14px;
		/* 初始宽度 */
		background: #3c9cff;
		/* 下划线颜色 */
		transition-duration: 300ms;
		border-radius: 2px;

	}

	.empty {
		margin-top: 120px;
	}

	.empty image {
		width: 176px;
		height: 176px;
	}

	.list .item {
		padding: 15px 12px 13px;
		margin-top: 10px;

		.title {
			padding-bottom: 10px;
			border-bottom: 1px solid #eee;
		}

		.else {
			width: 50%;
			align-items: center;
		}

		.else text:nth-of-type(2) {
			margin-left: 10px;
		}
	}
</style>